package com.kuang.config;

import com.kuang.pojo.Users;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @auther liuyang
 * @create 2021-10-17-17:40
 */
public class MyInterceptor implements HandlerInterceptor {
    //用来请求拦截，是否放行
    //true 表示放行，进入下一次拦截器
    //false 表示拦截，不会进入下一个拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求前，拦截处理");
        System.out.println("拦截的路径："+request.getRequestURI());
        return true;
    }

    //进行处理器拦截用的，它的执行时间是在处理器进行处理之后
    //也就是在Controller的方法调用之后执行，但是它会在
    //DispatcherServlet进行视图的渲染之前执行，也就是说在
    //这个方法中你可以对ModelAndView进行操作

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("userLogin");
        System.out.println(111);
        if(user == null){
            request.setAttribute("msg", "您还没有登录，请先登录！");
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                    .forward(request, response);
        }
    }

    //DispatcherServlet渲染了视图之后执行，用于清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("清理");
    }

}
